package com.atguigu.cloud.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

@Slf4j
@RestController
public class RateLimitController {

    @GetMapping("/rateLimit/byUrl")
    public String byUrl() {
        return "按rest地址限流测试OK";
    }

    @GetMapping("/rateLimit/byResource")
    @SentinelResource(value = "byResourceSentinelResource", blockHandler = "handleException")
    public String byResource() {
        return "按资源名称SentinelResource限流测试OK";
    }
    //自定义熔断机制
    public String handleException(BlockException exception) {
        return "服务不可用触发@SentinelResource启动\"+\"\\t\"+\"o(╥﹏╥)o";
    }

    @GetMapping("/rateLimit/doAction/{p1}")
    @SentinelResource(value = "doActionSentinelResource", blockHandler = "doActionBlockHandler",fallback = "doActionFallback")
    public String doAction(@PathVariable("p1")Integer p1){
        if (p1==0){
            throw new RuntimeException("参数不能为0");
        }
        return "doAction";
    }
    public String doActionBlockHandler(@PathVariable("p1") Integer p1, BlockException exception) {
        log.info("服务不可用触发@SentinelResource启动\"+\"\\t\"+\"o(╥﹏╥)o");
        return "服务不可用触发@SentinelResource启动\"+\"\\t\"+\"o(╥﹏╥)o";
    }

    public String doActionFallback(@PathVariable("p1") Integer p1, Throwable t){
        log.error("程序逻辑异常了:{}", t);
        return "程序逻辑异常了"+"\t"+t.getMessage();
    }

    @GetMapping("/testHotKey")
    @SentinelResource(value ="testHotKey",blockHandler = "dealHandler_testHotKey")
    public String testHotKey(@RequestParam(value="p1", required = false)String p1,
                             @RequestParam(value= "p2",required = false)String p2){
        return "--testHotKey";

    }
    public String dealHandler_testHotKey(String p1, String p2, BlockException exception){
        return "--dealHandler_testHotKey";
    }

}
